package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author: atguigu
 * @create: 2024-05-07 10:16
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties props;

    /**
     * 上传文件（专辑声音封面、用户头像等）
     *
     * @param file
     * @return 上传文件成功后在线地址用于前端预览图片
     */
    @Override
    public String fileUpload(MultipartFile file) {
        try {
            //1.验证文件是否为图片
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                throw new GuiguException(400, "图片文件有误！");
            }
            //2.验证图片文件大小（长宽限制900）
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width > 1500 || height > 1500) {
                throw new GuiguException(400, "图片尺寸过大！");
            }

            //3.将图片文件上传到MInIO中tingshu存储空间
            //3.1 生成随机唯一文件名称避免 格式：/日期/文件名称.后缀
            String folderName = DateUtil.today();
            String objectName = "/" + folderName + "/" + IdUtil.getSnowflakeNextId() + "." + FileNameUtil.extName(file.getOriginalFilename());
            //3.2 调用客户端对象上传文件方法
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(props.getBucketName()).object(objectName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            //4.拼接文件在线地址
            return props.getEndpointUrl() + "/" + props.getBucketName() + objectName;
        } catch (Exception e) {
            log.error("[专辑服务]文件上传异常：{}", e);
            throw new RuntimeException("[专辑服务]文件上传异常:" + e);
        }
    }
}
